package com.stars.easyms.datasource.mybatisplus;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisMapperAnnotationBuilder;
import com.stars.easyms.datasource.mybatis.EasyMsMapperRegistry;
import org.apache.ibatis.binding.BindingException;

/**
 * <p>className: EasyMsMybatisPlusMapperRegistry</p>
 * <p>description: EasyMs自定义mapper注册类</p>
 *
 * @author guoguifang
 * @version 1.7.0
 * @date 2020-11-01 11:57
 */
final class EasyMsMybatisPlusMapperRegistry extends EasyMsMapperRegistry {

    private MybatisConfiguration mybatisConfiguration;

    EasyMsMybatisPlusMapperRegistry(MybatisConfiguration config) {
        super(config);
        this.mybatisConfiguration = config;
    }

    @Override
    public <T> void addMapper(Class<T> type) {
        if (type.isInterface()) {
            if (hasMapper(type)) {
                throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
            }
            boolean loadCompleted = false;
            try {
                knownMappers.put(type, new EasyMsMybatisPlusMapperProxyFactory<>(type));
                MybatisMapperAnnotationBuilder parser = new MybatisMapperAnnotationBuilder(mybatisConfiguration, type);
                parser.parse();
                loadCompleted = true;
            } finally {
                if (!loadCompleted) {
                    knownMappers.remove(type);
                }
            }
        }
    }
}